#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import abort, g
from flask_restful import Resource, reqparse, marshal_with, fields

from src.api import api, meta_fields
from src.api.auth import self_only
from src.models.tag import Tag
from src.models.user import User
from src.helpers import paginate
from src.extensions import auth


tag_parser = reqparse.RequestParser()
tag_parser.add_argument('name', type=unicode, required=True)
tag_parser.add_argument('description', type=unicode, required=True)

tag_collection_parser = reqparse.RequestParser()
tag_collection_parser.add_argument('name', type=unicode, required=False)
tag_collection_parser.add_argument('description', type=unicode, required=False)


# Marshaled field definitions for task objects
tag_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'description': fields.String
}

# Marshaled field definitions for collections of task objects
tag_collection_fields = {
    'items': fields.List(fields.Nested(tag_fields)),
    'meta': fields.Nested(meta_fields),
}


class TagResource(Resource):
    @marshal_with(tag_fields)
    def get(self, tag_id=None):
        tag = Tag.get_by_id(tag_id)

        if not tag:
            abort(404)

        return tag

    @auth.login_required
    @marshal_with(tag_fields)
    def post(self, tag_id=None):
        update_tag = Tag.get_by_id(tag_id)
        tag = Tag.update(update_tag, **tag_parser.parse_args())
        return tag

    @auth.login_required
    @self_only
    def delete(self, tag_id=None):
        update_tag = Tag.get_by_id(tag_id)
        Tag.delete(update_tag)
        return 204


class TagCollectionResource(Resource):

    @marshal_with(tag_collection_fields)
    @paginate()
    def get(self):
        # Get the user's tags
        tags = Tag.query

        args = tag_collection_parser.parse_args()
        # fancy url argument query filtering!
        if args['title'] is not None:
            tags.filter_by(title=args['title'])

        return tags

    @auth.login_required
    @marshal_with(tag_fields)
    def post(self):
        args = tag_parser.parse_args()
        # user owns the task
        tag = Tag.create(**args)
        return tag, 201


api.add_resource(TagResource, '/tag/<int:tag_id>')  # tag 删改查
api.add_resource(TagCollectionResource, '/tag')  # tag 分页差，增
